'use strict';
const db = uniCloud.database();
const downloadMoney = 0.11
exports.main = async (event, context) => {

	var dbName = 'wx_user_earnings' //集合表名
	var filter = event.filter ? event.filter : {} //筛选条件
	var addData = event.addData //新增参数
	var addDatas = event.addDatas //新增多个
	var upData = event.upData //修改参数
	var dataIP = event.dataIP
	var timeStamp = new Date().getTime()
	var result = {}


	let list = await db.collection(dbName).where(filter).get()
	let userList = await db.collection('uni-id-users').where({
		openid: addData.user_id || upData.user_id
	}).get()
	if (userList.data.length == 0) {
		return {
			success: false,
			msg: '用户不存在'
		}
	}
	let userData = userList.data[0]
	dataIP.up_date = upData.up_date



	// 获取今天下载记录
	let todayDownloadRecord = await db.collection(dbName).where({
		user_id: filter.user_id,
		add_data: filter.add_data,
	}).get()
	var download_user1 = []
	// 筛选表里面的用户信息
	todayDownloadRecord.data.forEach(item => {
		download_user1.push(...item.download_user)
	})
	console.log(download_user1,'download_user1download_user1download_user1download_user1download_user1')
	// 今天当前下载用户
	let download_users = download_user1.filter(item => {
		return item.openid == upData.download_user.openid
	})
	console.log(download_users,'download_usersdownload_usersdownload_usersdownload_users')
	if (download_users.length === 0 && list.data.length == 0) {
		if (!addDatas) {
			addData.time = timeStamp
		}
		addData.download = 1
		addData.ip = [dataIP.cip]
		addData.ipInfo = [dataIP]
		addData.sum = addData.download * downloadMoney
		result = await db.collection(dbName).add(addData)
		if (result.inserted === 0) {
			// 删除失败
			return {
				success: false,
				msg: '操作失败'
			}
		}
		return {
			success: true,
			msg: '操作成功'
		}
	} else {
		if(list.data.length != 0 && download_users.length === 0){
			// 当前过滤的数据
			let item = list.data[0]
			let up_date = item.up_date
			if (download_users.length == 0) {
				// 没有下载过的用户 累加钱数和下载数据量
				upData.download = item.download + 1
				upData.up_date = [...item.up_date, upData.up_date]
				upData.sum = upData.download * downloadMoney
			}
			upData.ipInfo = [...item.ipInfo, dataIP]
			upData.download_user = [...item.download_user, upData.download_user]
			result = await db.collection(dbName).where(filter).update(upData)
			if (result.updated === 0) {
				// 删除失败
				return {
					success: false,
					msg: '操作失败'
				}
			}
			
		}
	
		
		return {
			success: true,
			msg: '操作成功'
		}
	}
};
